//
//  CLReadTextFastParser.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/8/13.
//

#import "CLReadTextFastParser.h"

@implementation CLReadTextFastParser

/// 异步解析本地链接
///
/// - Parameters:
///   - url: 本地文件地址
///   - completion: 解析完成
+ (void)parser:(NSURL *)url completion:(CLParserCompletion)completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
        CLReadModel *readModel = [self parser:url];
        
        dispatch_main_safe_async(^{
            CLSafeExecuteBlock(completion,readModel);
        });
    });
}
    
/// 解析本地链接
///
/// - Parameter url: 本地文件地址
/// - Returns: 阅读对象
+ (CLReadModel *)parser:(NSURL *)url {
        
    // 链接不为空且是本地文件路径
    if (url == nil || url.absoluteString.isEmpty || !url.isFileURL) { return nil; }
        
    // 获取文件后缀名作为 bookName
    NSString *bookName = [[url.absoluteString stringByRemovingPercentEncoding].lastPathComponent stringByDeletingPathExtension];
    bookName = StrNilHolder(bookName, @"");
        
        // bookName 作为 bookID
    NSString *bookID = bookName;
        
        // bookID 为空
    if (NULLString(bookID)) { return nil; }
    
    if (![CLReadModel isExist:bookID]) {
        
        // 解析数据
        NSString *content = [CLReadParser encode:url];
        
        // 解析失败
        if (NULLString(content)) { return nil; }
        
        // 阅读模型
        CLReadModel *readModel = [CLReadModel model: bookID];
        
        // 书籍类型
        readModel.bookSourceType = BookSourceTypeLocal;
        
        // 小说名称
        readModel.title = bookName;
        readModel.bookid = bookID;
        // 解析内容并获得章节列表
        [self parser:readModel content:content];
        
        // 解析内容失败
        if (readModel.chapterListModels == nil || readModel.chapterListModels.isEmpty) { return nil; }
        
        // 首章
        CLReadChapterListModel *chapterListModel = readModel.chapterListModels.firstObject;
        chapterListModel.bookid = bookName;
        // 加载首章
        CLReadChapterModel *chapterModel = [self parser:readModel chapterid:chapterListModel.chapterid];
        
        // 设置第一个章节为阅读记录
        [readModel.recordModel modify:chapterListModel.chapterid toPage:0 isSave:YES];
        
        // 保存
        [readModel save];
        
        return readModel;
    } else {
        return [CLReadModel model:bookID];
    }
}

/// 解析整本小说
///
/// - Parameters:
///   - bookID: 小说ID
///   - content: 小说内容
/// - Returns: 章节列表
+ (void)parser:(CLReadModel *)readModel content:(NSString *)content {
    
    // 章节列表
    NSMutableArray <CLReadChapterListModel *>*chapterListModels = [NSMutableArray array];

    // 章节范围列表 [章节ID:[章节优先级:章节内容Range]]
    NSMutableDictionary <NSString *, NSDictionary <NSString *, NSValue *>*>*ranges = [NSMutableDictionary dictionary];
    
    // 正则
    NSString *parten = @"第[0-9一二三四五六七八九十百千]*[章回].*";

    // 排版
    content = [CLReadParser contentTypesetting:content];

    // 正则匹配结果
    NSArray <NSTextCheckingResult *>*results = @[];

    // 开始匹配
    results = [content matchesByPattern:parten];

    // 解析匹配结果
    if (results && !results.isEmpty) {

        // 章节数量
        NSInteger count = results.count;

        // 记录最后一个Range
        NSRange lastRange = NSMakeRange(0, 0);

        // 有前言
        BOOL isHavePreface = YES;

        // 便利
        for (int i = 0; i < count; i++) {
            // 章节数量分析:
            // count + 1  = 匹配到的章节数量 + 最后一个章节
            // 1 + count + 1  = 第一章前面的前言内容 + 匹配到的章节数量 + 最后一个章节
            NSLog(@"章节总数: %@  当前正在解析: %@",@(count + 1),@(i + 1));
            NSRange range = NSMakeRange(0, 0);
            NSInteger location = 0;
            if (i < count) {
                
                range = results[i].range;
                
                location = range.location;
            }
            // 章节内容
            CLReadChapterListModel *chapterListModel = [[CLReadChapterListModel alloc]init];
            
            // 书ID
            chapterListModel.bookid = readModel.bookid;
            
            // 章节ID
            chapterListModel.chapterid = @(i + (isHavePreface?1:0)).stringValue;
            
            // 优先级
            NSInteger priority = i - (isHavePreface?0:1);
            
            if (i == 0) { // 前言
                
                // 章节名
                chapterListModel.title = @"开始";
                
                // 内容Range
                ranges[chapterListModel.chapterid] = @{@(priority).stringValue:[NSValue valueWithRange:NSMakeRange(0, location)]};
                
                // 内容
                NSString *t_content = [content substringWithRange:(NSMakeRange(0, location))];
                
                // 记录
                lastRange = range;
                
                // 没有内容则不需要添加列表
                if (NULLString(t_content)) {
                    
                    isHavePreface = NO;
                    
                    continue;
                }
                
            }else if (i == count) { // 结尾
                
                // 章节名
                chapterListModel.title = [content substringWithRange:lastRange];
                
                // 内容(不包含章节名)
                ranges[chapterListModel.chapterid] =  @{@(priority).stringValue:[NSValue valueWithRange:NSMakeRange(lastRange.location + lastRange.length, content.length - lastRange.location - lastRange.length)]};
                
            }else { // 中间章节
                
                // 章节名
                chapterListModel.title = [content substringWithRange:lastRange];
                
                // 内容(不包含章节名)
                ranges[chapterListModel.chapterid] = @{@(priority).stringValue:[NSValue valueWithRange:NSMakeRange(lastRange.location + lastRange.length, location - lastRange.location - lastRange.length)]};
            }
            // 记录
            lastRange = range;
            
            // 通过章节内容生成章节列表
            [chapterListModels addObject:chapterListModel];
        }
    } else {
        // 章节内容
        CLReadChapterListModel *chapterListModel = [[CLReadChapterListModel alloc]init];
        
        // 章节名
        chapterListModel.name = @"开始";
        
        // 书ID
        chapterListModel.bookid = readModel.bookid;
        
        // 章节ID
        chapterListModel.chapterid = @"1";
        
        // 优先级
        NSInteger priority = 0;
        
        // 内容
        ranges[chapterListModel.chapterid] = @{@(priority).stringValue:[NSValue valueWithRange:NSMakeRange(0, content.length)]};
        
        // 添加章节列表模型
        [chapterListModels addObject:chapterListModel];
    }
    // 小说全文
    readModel.fullText = content;
    
    // 章节列表
    readModel.chapterListModels = chapterListModels;
    
    // 章节内容范围
    readModel.ranges = ranges;
}

/// 获取单个指定章节
+ (CLReadChapterModel *)parser:(CLReadModel *)readModel chapterid:(NSString *)chapterid {
    return [self parser:readModel chapterid:chapterid isUpdateFont:YES];
}

+ (CLReadChapterModel *)parser:(CLReadModel *)readModel chapterid:(NSString *)chapterid isUpdateFont:(BOOL)isUpdateFont {
    
    // 获得[章节优先级:章节内容Range]
    NSDictionary *rangeDict = readModel.ranges[chapterid];
  
    // 没有了
    if (rangeDict != nil) {
        
        // 当前优先级
        NSInteger priority = [rangeDict.allKeys.firstObject integerValue];
        
        // 章节内容范围
        NSValue *value = rangeDict.allValues.firstObject;
        NSRange range = [value rangeValue];
        
        // 当前章节
        CLReadChapterListModel *chapterListModel = readModel.chapterListModels[priority];
        
        /// 第一个章节
        BOOL isFirstChapter = (priority == 0);
        
        /// 最后一个章节
        BOOL isLastChapter = (priority == (readModel.chapterListModels.count - 1));
        
        // 上一个章节ID
        NSString *previousChapterID = isFirstChapter ? CL_READ_NO_MORE_CHAPTER : readModel.chapterListModels[priority - 1].chapterid;
        
        // 下一个章节ID
        NSString *nextChapterID = isLastChapter ? CL_READ_NO_MORE_CHAPTER : readModel.chapterListModels[priority + 1].chapterid;
        
        // 章节内容
        CLReadChapterModel *chapterModel = [[CLReadChapterModel alloc]init];
        
        // 书ID
        chapterModel.bookid = chapterListModel.bookid;
        if (NULLString(chapterModel.bookid)) {
            chapterModel.bookid = readModel.bookName;
        }
        // 章节ID
        chapterModel.chapterid = chapterListModel.chapterid;
        
        // 章节名
        chapterModel.name = chapterListModel.name;
        
        // 优先级
        chapterModel.priority = priority;
        
        // 上一个章节ID
        chapterModel.previousChapterID = previousChapterID;
        
        // 下一个章节ID
        chapterModel.nextChapterID = nextChapterID;
        
        // 章节内容
        chapterModel.content = [NSString stringWithFormat:@"%@%@",CL_READ_PH_SPACE, [[readModel.fullText substringWithRange:range] removeSEHeadAndTail]];

        // 保存
        if (isUpdateFont) {
            [chapterModel updateFont];
        }else{
            [chapterModel save];
        }
        
        // 返回
        return chapterModel;
    }
    return nil;
}
@end
